import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dio/dio.dart';
import '../config/simple_dio_config.dart';
import '../services/toast_service.dart';

class ApiDemoPage extends ConsumerStatefulWidget {
  const ApiDemoPage({super.key});

  @override
  ConsumerState<ApiDemoPage> createState() => _ApiDemoPageState();
}

class _ApiDemoPageState extends ConsumerState<ApiDemoPage> {
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  late Dio dio;
  
  List<Map<String, dynamic>> _users = [];
  bool _isLoading = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    // 创建包含异常拦截器的Dio实例
    dio = SimpleDioConfig.createDio();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('API异常拦截演示'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => _fetchUsers(),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 操作按钮区域
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'API异常拦截测试',
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                    const SizedBox(height: 16),
                    
                    // API测试按钮
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ElevatedButton.icon(
                          onPressed: _isLoading ? null : _fetchUsers,
                          icon: _isLoading 
                              ? const SizedBox(
                                  width: 16,
                                  height: 16,
                                  child: CircularProgressIndicator(strokeWidth: 2),
                                )
                              : const Icon(Icons.download),
                          label: Text(_isLoading ? '加载中...' : '获取用户列表'),
                        ),
                        ElevatedButton.icon(
                          onPressed: _isLoading ? null : _test404Error,
                          icon: const Icon(Icons.error_outline, color: Colors.orange),
                          label: const Text('测试404错误'),
                        ),
                        ElevatedButton.icon(
                          onPressed: _isLoading ? null : _test500Error,
                          icon: const Icon(Icons.warning, color: Colors.red),
                          label: const Text('测试500错误'),
                        ),
                        ElevatedButton.icon(
                          onPressed: _isLoading ? null : _testNetworkError,
                          icon: const Icon(Icons.wifi_off, color: Colors.red),
                          label: const Text('测试网络错误'),
                        ),
                        ElevatedButton.icon(
                          onPressed: () => _showToastExamples(),
                          icon: const Icon(Icons.notifications),
                          label: const Text('Toast示例'),
                        ),
                      ],
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 添加用户表单
                    Text(
                      '添加新用户（测试POST请求）',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _nameController,
                            decoration: const InputDecoration(
                              labelText: '姓名',
                              border: OutlineInputBorder(),
                              isDense: true,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: TextField(
                            controller: _emailController,
                            decoration: const InputDecoration(
                              labelText: '邮箱',
                              border: OutlineInputBorder(),
                              isDense: true,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        ElevatedButton(
                          onPressed: _isLoading ? null : _addUser,
                          child: const Text('添加'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 用户列表显示区域
            Expanded(
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '用户列表 (${_users.length})',
                            style: Theme.of(context).textTheme.titleLarge,
                          ),
                          if (_errorMessage != null)
                            IconButton(
                              icon: const Icon(Icons.error_outline, color: Colors.red),
                              onPressed: () {
                                ToastService.showError(_errorMessage!);
                              },
                            ),
                        ],
                      ),
                      const SizedBox(height: 16),
                      
                      Expanded(
                        child: _users.isEmpty
                            ? Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.people_outline,
                                      size: 64,
                                      color: Colors.grey[400],
                                    ),
                                    const SizedBox(height: 16),
                                    Text(
                                      _isLoading 
                                          ? '正在加载用户列表...' 
                                          : '暂无用户数据\n点击"获取用户列表"按钮开始测试',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        color: Colors.grey[600],
                                        fontSize: 16,
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            : ListView.builder(
                                itemCount: _users.length,
                                itemBuilder: (context, index) {
                                  final user = _users[index];
                                  return Card(
                                    margin: const EdgeInsets.symmetric(vertical: 4),
                                    child: ListTile(
                                      leading: CircleAvatar(
                                        child: Text((user['name'] ?? 'U')[0]),
                                      ),
                                      title: Text(user['name'] ?? 'Unknown'),
                                      subtitle: Text(user['email'] ?? 'No email'),
                                      trailing: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          IconButton(
                                            icon: const Icon(Icons.edit, size: 20),
                                            onPressed: () => _editUser(user),
                                          ),
                                          IconButton(
                                            icon: const Icon(Icons.delete, size: 20, color: Colors.red),
                                            onPressed: () => _deleteUser(user['id']),
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _setLoading(bool loading) {
    setState(() => _isLoading = loading);
  }

  // 获取用户列表
  Future<void> _fetchUsers() async {
    print('🧪 开始获取用户列表');
    _setLoading(true);
    setState(() => _errorMessage = null);
    
    try {
      final response = await dio.get('/users');
      print('🧪 用户列表获取成功: ${response.statusCode}');
      
      if (response.data is List) {
        setState(() {
          _users = List<Map<String, dynamic>>.from(response.data);
          _isLoading = false;
        });
        
        // 显示成功Toast
        ToastService.showSuccess('用户列表获取成功！共${_users.length}个用户');
      }
    } catch (e) {
      print('🧪 用户列表获取失败: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '获取用户列表失败';
      });
      // 错误已经由拦截器处理并显示Toast
    }
  }

  // 测试404错误
  Future<void> _test404Error() async {
    print('🧪 开始测试404错误');
    _setLoading(true);
    
    try {
      await dio.get('/posts/999999'); // 不存在的资源
      ToastService.showInfo('意外：404请求竟然成功了？');
    } catch (e) {
      print('🧪 404错误测试完成: $e');
      // 错误已经由拦截器处理并显示弹框
    } finally {
      _setLoading(false);
    }
  }

  // 测试500错误
  Future<void> _test500Error() async {
    print('🧪 开始测试500错误');
    _setLoading(true);
    
    try {
      // 创建临时Dio实例来请求httpbin的500状态码
      final tempDio = Dio();
      tempDio.interceptors.addAll(dio.interceptors);
      await tempDio.get('https://httpbin.org/status/500');
      ToastService.showInfo('意外：500请求竟然成功了？');
    } catch (e) {
      print('🧪 500错误测试完成: $e');
      // 错误已经由拦截器处理并显示弹框
    } finally {
      _setLoading(false);
    }
  }

  // 测试网络错误
  Future<void> _testNetworkError() async {
    print('🧪 开始测试网络错误');
    _setLoading(true);
    
    try {
      // 请求不存在的域名
      final tempDio = Dio();
      tempDio.interceptors.addAll(dio.interceptors);
      await tempDio.get('https://this-domain-does-not-exist-12345.com/api');
      ToastService.showInfo('意外：网络错误请求竟然成功了？');
    } catch (e) {
      print('🧪 网络错误测试完成: $e');
      // 错误已经由拦截器处理并显示弹框
    } finally {
      _setLoading(false);
    }
  }

  // 添加用户
  Future<void> _addUser() async {
    final name = _nameController.text.trim();
    final email = _emailController.text.trim();
    
    if (name.isEmpty || email.isEmpty) {
      ToastService.showWarning('请填写完整的用户信息');
      return;
    }
    
    print('🧪 开始添加用户: $name, $email');
    _setLoading(true);
    
    try {
      final response = await dio.post('/users', data: {
        'name': name,
        'email': email,
      });
      
      print('🧪 用户添加成功: ${response.statusCode}');
      
      // 添加到本地列表
      final newUser = response.data as Map<String, dynamic>;
      setState(() {
        _users.add(newUser);
        _isLoading = false;
      });
      
      // 清空表单
      _nameController.clear();
      _emailController.clear();
      
      // 显示成功Toast
      ToastService.showSuccess('用户添加成功！', title: '操作成功');
      
    } catch (e) {
      print('🧪 用户添加失败: $e');
      _setLoading(false);
      // 错误已经由拦截器处理并显示弹框
    }
  }

  // 编辑用户
  void _editUser(Map<String, dynamic> user) {
    ToastService.showInfo('编辑功能演示: ${user['name']}', title: '功能演示');
  }

  // 删除用户
  Future<void> _deleteUser(int? userId) async {
    if (userId == null) return;
    
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个用户吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('删除'),
          ),
        ],
      ),
    );
    
    if (confirmed == true) {
      print('🧪 开始删除用户: $userId');
      _setLoading(true);
      
      try {
        await dio.delete('/users/$userId');
        
        // 从本地列表删除
        setState(() {
          _users.removeWhere((user) => user['id'] == userId);
          _isLoading = false;
        });
        
        // 显示成功Toast
        ToastService.showSuccess('用户删除成功！', title: '操作成功');
        
      } catch (e) {
        print('🧪 用户删除失败: $e');
        _setLoading(false);
        // 错误已经由拦截器处理并显示弹框
      }
    }
  }

  void _showToastExamples() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Toast 示例'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.check_circle, color: Colors.green),
              title: const Text('成功提示'),
              onTap: () {
                Navigator.of(context).pop();
                ToastService.showSuccess('这是一个成功的提示消息');
              },
            ),
            ListTile(
              leading: const Icon(Icons.error, color: Colors.red),
              title: const Text('错误提示'),
              onTap: () {
                Navigator.of(context).pop();
                ToastService.showError('这是一个错误的提示消息');
              },
            ),
            ListTile(
              leading: const Icon(Icons.warning, color: Colors.orange),
              title: const Text('警告提示'),
              onTap: () {
                Navigator.of(context).pop();
                ToastService.showWarning('这是一个警告的提示消息');
              },
            ),
            ListTile(
              leading: const Icon(Icons.info, color: Colors.blue),
              title: const Text('信息提示'),
              onTap: () {
                Navigator.of(context).pop();
                ToastService.showInfo('这是一个信息的提示消息');
              },
            ),
            ListTile(
              leading: const Icon(Icons.hourglass_empty, color: Colors.grey),
              title: const Text('加载提示'),
              onTap: () {
                Navigator.of(context).pop();
                ToastService.showLoading('正在处理，请稍候...');
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }
}
